package com.mmall.controller.portal;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IOrderService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/order/")
public class OrderController {

    @Autowired
    private IOrderService iOrderService;

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);


    /**
     * 创建订单
     * @param session
     * @param shipping
     * @return
     */
    @RequestMapping("creatOrdre.do")
    @ResponseBody
    public  ServerResponse creatOrdre(HttpSession session,Integer shipping){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        return  iOrderService.creatOrdre(user.getId(),shipping);
    }


    /**
     * 取消订单
     * @param session
     * @param orderOn
     * @return
     */
    @RequestMapping("cancelOrdre.do")
    @ResponseBody
    public  ServerResponse cancelOrdre(HttpSession session,Long orderOn){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        return  iOrderService.cancelOrdre(user.getId(),orderOn);
    }


    /**
     * 勾选订单的全部详情页
     * @param session
     * @return
     */
    @RequestMapping("cancelOrdre.do")
    @ResponseBody
    public  ServerResponse selectOrdre(HttpSession session){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        return  iOrderService.selectOrdre(user.getId());
    }


    /**
     *
     * 前端商品订单的详情页
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("cancelOrdre.do")
    @ResponseBody
    public  ServerResponse detailOrder(HttpSession session,Long orderNo){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        return  iOrderService.detailOrder(user.getId(),orderNo);
    }


    @RequestMapping("getOrderList.do")
    @ResponseBody
    public  ServerResponse getOrderList (HttpSession session, @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo, @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        return  iOrderService.getOrderList(user.getId(),pageNo,pageSize);
    }



    /**
     * 生成支付二维码
     *
     * @param session
     * @param orderNo
     * @param request
     * @return
     */
    @RequestMapping("payOrder.do")
    @ResponseBody
    public ServerResponse payOrder(HttpSession session, Long orderNo, HttpServletRequest request) {

        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        String path = request.getSession().getServletContext().getRealPath("upload");

        return iOrderService.payOrder(path, user.getId(), orderNo);

    }


    /**
     * 支付宝回调信息
     *
     * @param request
     * @return
     */
    @RequestMapping("callbackeOrder.do")
    @ResponseBody
    public Object callbackeOrder(HttpServletRequest request) {

        Map<String, String> parMap = Maps.newHashMap();

        //获得支付宝回调的所有信息
        Map<String, String[]> map = request.getParameterMap();

        for (Map.Entry<String, String[]> stringEntry : map.entrySet()) {


            String key = stringEntry.getKey();

            String[] value = stringEntry.getValue();


            String valueStr = "";

            for (int i = 0; i < value.length; i++) {
                //组装信息的valueStr信息,把所有的value都存储到
                valueStr = (i == value.length - 1) ? valueStr + value[i] : valueStr + value[i] + ",";
            }
            parMap.put(key, valueStr);
        }

        //日志打印对应的信息
        logger.info("支付宝回调,sign:{},trade_status:{},参数:{}", parMap.get("sign"), parMap.get("trade_status"), parMap.toString());

        //logger.info("支付回调{},");


        try {
            //判断支付宝回调的情况,查询他
            boolean b = AlipaySignature.rsaCheckV2(parMap, Configs.getAlipayPublicKey(), "uft-8", Configs.getSignType());
            if (!b) {
                return ServerResponse.createByErrorMessage("支付回调异常");
            }


        } catch (AlipayApiException e) {
            logger.error("支付回调异常", e);

        }

        ServerResponse serverResponse = iOrderService.callbackeOrder(parMap);
        if (serverResponse.isSuccess()) {
            return Const.AlipayCallback.RESPONSE_SUCCESS;
        }
        return Const.AlipayCallback.RESPONSE_FAILED;

    }


    /**
     * 查询支付状态
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("quseryOrder.do")
    @ResponseBody
    public ServerResponse<Boolean> quseryOrder(HttpSession session, Long orderNo) {

        //判断用户是否登录
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        ServerResponse<Boolean> booleanServerResponse = iOrderService.quseryOrder(user.getId(), orderNo);

        if (booleanServerResponse.isSuccess()){
            return  ServerResponse.createBySuccess(true);
        }
        return  ServerResponse.createBySuccess(false);
    }

}